<?php
namespace app\farm\controller;
use app\ApiRest;


use app\farm\model\BalanceWater;
use app\farm\model\Car;

use app\farm\model\Config;
use app\farm\model\CouponRecord;
use app\farm\model\FinanceWater;
use app\farm\model\SystemInfo;
use app\farm\model\Wallet;
use app\massage\model\CarAtvRecord;
use app\farm\model\Address;
use app\farm\model\User;
use app\farm\model\Farmer;
use app\shop\model\DistributionList;
use think\App;

use think\facade\Db;



class IndexUser extends ApiRest
{

    protected $model;

    protected $address_model;

    protected $record_model;

    protected $coupon_record_model;

    protected $car_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new User();

        $this->address_model = new Address();

        $this->record_model = new CarAtvRecord();

        $this->car_model = new Car();

        $this->coupon_record_model = new CouponRecord();
        //积分到账
       // point_success($this->_uniacid);


    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function index(){

        if(empty($this->getUserId())){

            return $this->success([]);

        }

        $data = $this->model->dataInfo(['id'=>$this->getUserId()]);

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['type','=',1];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $farmer_model = new Farmer();
        //查看是否是团长
        $cap_info = $farmer_model->dataInfo($cap_dis);
        //-1表示未申请团长，1申请中，2已通过，3取消,4拒绝
        $data['farmer_status'] = !empty($cap_info)?$cap_info['status']:-1;

        $data['sh_text'] = !empty($cap_info)?$cap_info['sh_text']:'';

        $where[] = ['user_id','=',$this->getUserId()];

        $where[] = ['status','in',[1,2,3,4]];

        $distri_model = new DistributionList();

        $fx = $distri_model->dataInfo($where);

        $data['fx_status'] = !empty($fx)?$fx['status']:-1;

        $data['fx_text']   = !empty($fx)?$fx['sh_text']:'';
        //优惠券数
     //   $data['coupon_count'] = $this->coupon_record_model->couponCount($this->getUserId());
        $water_model = new FinanceWater();
        //冻结金额
        $data['frozen_cash'] = $water_model->landordFrozenCash($this->getUserId());

        $data['balance_cash']= round($data['balance'] - $data['wallet_cash'],2);

        $data['balance'] += $data['frozen_cash'];

        $data['balance'] = round($data['balance'],2);

        $info_model = new SystemInfo();
        //是否含有未读消息
        $data['no_read_info'] = $info_model->userHaveNews($this->getUserId(),$this->_uniacid);

        return $this->success($data);

    }







    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:54
     * @功能说明:用户地址列表
     */
    public function addressList(){

        $dis[] = ['user_id','=',$this->getUserId()];

        $dis[] = ['status','>',-1];

        $data = $this->address_model->dataList($dis,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:57
     * @功能说明:用户地址详情
     */
    public function addressInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->address_model->dataInfo($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:58
     * @功能说明:添加用户地址
     */
    public function addressAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $input['user_id'] = $this->getUserId();

        $res = $this->address_model->dataAdd($input);

        if($input['status']==1){

            $id = $this->address_model->getLastInsID();

            $this->address_model->updateOne($id);
        }

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:58
     * @功能说明:添加用户地址
     */
    public function addressUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $res = $this->address_model->dataUpdate($dis,$input);

        if(!empty($input['status'])&&$input['status']==1){

            $this->address_model->updateOne($input['id']);

        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-11 22:54
     * @功能说明:获取默认地址
     */
    public function getDefultAddress(){

        $address_model = new Address();

        $address = $address_model->dataInfo(['user_id'=>$this->getUserId(),'status'=>1]);

        return $this->success($address);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:13
     * @功能说明:删除地址
     */
    public function addressDel(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $res = $this->address_model->where($dis)->delete();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 13:56
     * @功能说明:修改用户信息 授权微信信息等
     */
    public function userUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $this->getUserId()
        ];

        if(isset($input['coupon_atv_id'])){

            unset($input['coupon_atv_id']);
        }

        if(isset($input['watermark'])){

            unset($input['watermark']);
        }

        if(isset($input['openId'])){

            unset($input['openId']);

        }

        if(isset($input['unionId'])){

            unset($input['unionId']);

        }
        $res = $this->model->dataUpdate($dis,$input);

        $user_info = $this->model->dataInfo(['id'=>$this->getUserId()]);

        setCache($this->autograph, $user_info, 7200, $this->_uniacid);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-22 14:08
     * @功能说明:用户信息
     */
    public function userInfo(){

        if(empty($this->getUserId())){

            return $this->success([]);

        }

        $data = $this->model->dataInfo(['id'=>$this->getUserId()]);

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['type','=',1];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $farmer_model = new \app\farm\model\Farmer();
        //查看是否是团长
        $cap_info = $farmer_model->dataInfo($cap_dis);
        //-1表示未申请团长，1申请中，2已通过，3取消,4拒绝
        $data['farmer_status'] = !empty($cap_info)?$cap_info['status']:-1;

        $data['sh_text'] = !empty($cap_info)?$cap_info['sh_text']:'';

        $data['balance_cash']= round($data['balance'] - $data['wallet_cash'],2);

        $where[] = ['user_id','=',$this->getUserId()];

        $where[] = ['status','in',[1,2,3,4]];

        $distri_model = new DistributionList();

        $fx = $distri_model->dataInfo($where);

        $data['fx_status'] = !empty($fx)?$fx['status']:-1;

        $data['fx_text']   = !empty($fx)?$fx['sh_text']:'';

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-22 13:35
     * @功能说明:申请认证农场主
     */
    public function applyFarmer(){

        $input = $this->_input;

        $farmer_model = new Farmer();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','>',-1];

        $cap_dis[] = ['type','=',1];

        $cap_info = $farmer_model->dataInfo($cap_dis);

        if(!empty($cap_info)&&in_array($cap_info['status'],[1,2,3])){

            $this->errorMsg('你已经申请过农场主了，');
        }

        $input['uniacid'] = $this->_uniacid;

        $input['user_id'] = $this->getUserId();

        $input['status']  = 1;

        $input['imgs']  = !empty($input['imgs'])?implode(',',$input['imgs']):'';

        $input['idcard_imgs']  = !empty($input['idcard_imgs'])?implode(',',$input['idcard_imgs']):'';

        if(!empty($cap_info)&&$cap_info['status']==4){

            $res = $farmer_model->dataUpdate(['id'=>$cap_info['id']],$input);

        }else{

            $res = $farmer_model->dataAdd($input);

        }

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-26 10:43
     * @功能说明:农场主详情
     */
    public function farmerInfo(){

        if(empty($this->getUserId())){

            return $this->success([]);

        }

        $farmer_model = new Farmer();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','>',-1];

        $cap_dis[] = ['type','=',1];

        $cap_info = $farmer_model->dataInfo($cap_dis);

        return $this->success($cap_info);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-07-08 11:51
     * @功能说明:用户优惠券列表
     */
    public function userCouponList(){

        $input = $this->_param;

        $this->coupon_record_model->initCoupon($this->_uniacid);

        $dis = [

            'user_id' => $this->getUserId(),

            'status'  => $input['status'],

          //  'is_show' => 1
        ];

        $data = $this->coupon_record_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

                $v['use_time']   = date('Y.m.d H:i',$v['use_time']);

            }
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-16 22:09
     * @功能说明:删除优惠券
     */
    public function couponDel(){

        $input = $this->_input;

        $coupon = $this->coupon_record_model->dataInfo(['id'=>$input['coupon_id']]);

        if($coupon['status']==1){

            $this->errorMsg('待使用待卡券不能删除');
        }

        $res = $this->coupon_record_model->dataUpdate(['id'=>$input['coupon_id']],['is_show'=>0]);

        return $this->success($res);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-25 17:40
     * @功能说明：生产二维码
     */

    public function atvQr(){

        $input = $this->_input;

        $key = 'atv_coupon'.$input['coupon_atv_id'];

        $qr  = getCache($key,$this->_uniacid);

        if(empty($qr)){

//            $qr_insert = [
//
//                'coupon_atv_id' => $input['coupon_atv_id']
//            ];
            //获取二维码
            $qr = $this->model->orderQr($input,$this->_uniacid);

            setCache($key,$qr,86400,$this->_uniacid);
        }

        return $this->success($qr);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-14 19:22
     * @功能说明:授权手机号
     */
    public function reportPhone ()
    {

        $params = $this->_input;

        $encryptedData = $params[ 'encryptedData' ];

        $iv            = $params[ 'iv' ];

        $config    = longbingGetAppConfig($this->_uniacid);

        $appid     = $config[ 'appid' ];

       // $appsecret = $config[ 'app_secret' ];

        $session_key = $this->model->where(['id'=>$this->getUserId()])->value('session_key');

        if(empty($session_key)){

            $this->errorMsg('need login',401);
        }
        $data = null;
        //  解密
        $errCode = decryptDataLongbing( $appid, $session_key, $encryptedData, $iv, $data );

        if ( $errCode == 0 )
        {
            $data = json_decode( $data, true );

            $phone = $data[ 'purePhoneNumber' ];

        }
        else
        {
            return $this->error( $errCode );
        }

        $res = $this->model->dataUpdate(['id'=>$this->getUserId()],['phone'=>$phone]);

        $user_info = $this->model->dataInfo(['id'=>$this->getUserId()]);

        setCache($this->autograph, $user_info, 7200, $this->_uniacid);

        return $this->success($phone);
    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:46
     * @功能说明:添加到购物车
     */
    public function addCar(){

        $input = $this->_input;

        $is_show_del = !empty($input['is_show_del'])?$input['is_show_del']:1;

        if($is_show_del==1){

            $this->car_model->where(['user_id'=>$this->getUserId(),'is_show'=>2])->delete();
        }

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'farmer_id' => !empty($input['farmer_id'])?$input['farmer_id']:0,

            'goods_id'=> $input['goods_id'],

            'spe_id'  => !empty($input['spe_id'])?$input['spe_id']:0,

            'type'    => $input['type'],

            'is_show' => !empty($input['is_show'])?$input['is_show']:1,
        ];

        $info = $this->car_model->dataInfo($insert);
        //增加数量
        if(!empty($info)){

            $res = $this->car_model->dataUpdate(['id'=>$info['id']],['goods_num'=>$info['goods_num']+$input['goods_num']]);

            $id  = $info['id'];


        }else{
            //添加到购物车
            $insert['goods_num'] = $input['goods_num'];

            $insert['status']    = 1;

            $res = $this->car_model->dataAdd($insert);

            $id  = $this->car_model->getLastInsID();

        }

        return $this->success($id);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:54
     * @功能说明:删除购物车
     */
    public function delCar(){

        $input = $this->_input;

        $info = $this->car_model->dataInfo(['id'=>$input['id']]);
        //加少数量
        if($info['goods_num']>$input['goods_num']){

            $res = $this->car_model->dataUpdate(['id'=>$info['id']],['goods_num'=>$info['goods_num']-$input['goods_num']]);

        }else{

            $res = $this->car_model->where(['id'=>$info['id']])->delete();
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 10:39
     * @功能说明:
     */
    public function carUpdate(){

        $input = $this->_input;

        $res = $this->car_model->where('id','in',$input['id'])->update(['status'=>$input['status']]);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:59
     * @功能说明:批量删除购物车
     */
    public function delSomeCar(){

        $input = $this->_input;

        $dis = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'type'    => $input['type']

        ];

        $where = [];

        if(!empty($input['id'])){

            $where[] = ['id','in',$input['id']];
        }

        $res = $this->car_model->where($dis)->where($where)->delete();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-10 11:28
     * @功能说明:用户消费流水记录
     */
    public function userConsumeWater(){

        $input = $this->_param;

        $dis[] = ['user_id','=',$this->getUserId()];

        if(isset($input['add'])){

            $dis[] = ['add','=',$input['add']];
        }

        if(!empty($input['start_time'])&&!empty($input['end_time'])){

            $dis[] = ['create_time','between',"{$input['start_time']},{$input['end_time']}"];

        }

        $water_model = new BalanceWater();

        $data = $water_model->indexList($dis);

        return $this->success($data);

    }





    /**
     * @author chenniang
     * @DataTime: 2022-07-21 17:08
     * @功能说明:申请分销商
     */
    public function applyReseller(){

        $input = $this->_input;

        $distribution_model = new DistributionList();

        $dis[] = ['status','>',-1];

        $dis[] = ['user_id','=',$this->getUserId()];

        $find = $distribution_model->dataInfo($dis);

        if(!empty($find)&&in_array($find['status'],[1,2,3])){

            $this->errorMsg('你已经申请');

        }

        $insert = [

            'uniacid'  => $this->_uniacid,

            'user_id'  => $this->getUserId(),

            'user_name'=> $input['user_name'],

            'mobile'   => $input['mobile'],

            'status'   => 1,

        ];

        if(!empty($find)&&$find['status']==4){

            $res = $distribution_model->dataUpdate(['id'=>$find['id']],$insert);

        }else{

            $res = $distribution_model->dataAdd($insert);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-26 14:07
     * @功能说明:绑定分销商
     */
    public function bindReseller(){

        $input = $this->_input;

        $dis = [

            'fx_code' => $input['fx_code'],

            'uniacid' => $this->_uniacid
        ];

        $data = $this->model->dataInfo($dis);

        if(empty($data)){

            $this->errorMsg('邀请码无效');
        }

        if(!empty($this->getUserInfo()['pid'])){

            $this->errorMsg('你已经绑定分销商');

        }

        $update = [

            'pid' => $data['id']
        ];

        $res = $this->model->dataUpdate(['id'=>$this->getUserId()],$update);

        return $this->success($res);
    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:39
     * @功能说明:分销商详情
     */
    public function resellerInfo(){

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $distribution_model = new DistributionList();

        $cap_info = $distribution_model->dataInfo($cap_dis);

        return $this->success($cap_info);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-23 11:38
     * @功能说明:获取app下载地址
     */
    public function getAppDownloadQr(){

        $data = getCode($this->_uniacid,'www.baidu.com');

        return $this->success($data);
    }




    /**
     * @author chenniang
     * @DataTime: 2022-03-14 11:55
     * @功能说明:发送验证码
     */
    public function sendShortMsg(){

        $input = $this->_input;
        //验证码验证
        $config = new Config();

        $dis = [

            'uniacid' =>$this->_uniacid,

            'phone'   => $input['phone']
        ];

        $find = $this->model->dataInfo($dis);

        if(!empty($find)){

            $this->errorMsg('该手机号已经被绑定');
        }

        $res = $config->sendSms($input['phone'],$this->_uniacid);

        if(!empty($res['Message'])&&$res['Message']=='OK'){

            return $this->success(1);

        }else{

            return $this->error($res['Message']);

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-26 10:29
     * @功能说明:判断用户手机号
     */
    public function bindUserPhone(){

        $input = $this->_input;

        $dis = [

            'uniacid' =>$this->_uniacid,

            'phone'   => $input['phone']
        ];

        $find = $this->model->dataInfo($dis);

        if(!empty($find)){

            $this->errorMsg('该手机号已经被绑定');
        }

        $short_code = getCache($input['phone'],$this->_uniacid);
        //验证码验证手机号
        if($input['short_code']!=$short_code){

            return $this->error('验证码错误');

        }

        $res = $this->model->dataUpdate(['id'=>$this->getUserId()],$dis);

        $user = $this->getUserInfo();

        $user['phone'] = $input['phone'];

        $key = 'longbing_user_autograph_' . $user['id'];

        $key = md5($key);

        setCache($key, $user, 7200, $this->_uniacid);

        return $this->success($res);

    }




    /**
     * @author chenniang
     * @DataTime: 2022-08-26 15:45
     * @功能说明:通过分销码查找分销商
     */
    public function fxcodeUser(){

        $input = $this->_param;

        $dis = [

            'is_fx'   => 1,

            'fx_code' => $input['fx_code'],

            'uniacid' => $this->_uniacid
        ];

        $data = $this->model->dataInfo($dis);

        if(!empty($data)){

            $fx_model = new DistributionList();

            $data['fx_name'] = $fx_model->where(['user_id'=>$data['id'],'status'=>2])->value('user_name');

        }

        return $this->success($data);

    }





}
